package com.dminvoicemanager;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import com.dminvoicemanager.printdoc.DM_Print_Receipt;
import com.dminvoicemanager.printdoc.DM_Print_StockLoading;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class DM_Cash_Cheque_Receipt extends Activity {
	String TagId;
	private String DBNAME = "dminvoicemanager.db";
	// Master Tables
	private String USER_SETTINGS = "usersettings";
	private String ITEM_AREA = "fArea";
	private String ITEM_COMPANY_SETTING = "fCompanySetting";
	private String ITEM_CONTROL = "fControl";
	private String ITEM_DEBTOR = "fDebtor";
	private String ITEM_LOC_DETAILS = "fItemLoc";
	private String ITEM_LOCATION = "fLocation";
	private String ITEM_PRICE = "fItemPri";
	private String ITEMS = "fItems";
	private String INV_COMPANY_BRANCH = "FCompanyBranch";
	private String INV_SAL_REP = "fSalRep";
	private String SALES_ORD_REASON = "fReason";
	private String SALES_REP_ROUTE = "fRoute";
	private String BANK_DETAILS = "fBank";

	// Main Invoice
	private String TEMP_REP_INVOICESUMERY = "frepInvoiceSumery";
	private String INV_DETAILS = "FinvDet";
	private String INV_HEADER = "FinvHed";

	// Stock Loading
	private String TEMP_STOCK_LOADING_SUMMARY = "frepStockLoadingSummary";
	private String STOCK_LOAD_HEAD = "fLoadhed";
	private String STOCK_LOAD_DETAIL = "fLoadDet";

	// Stock Loading
	private String STOCK_ORDER_INVOICESUMERY = "fstockordInvoiceSumery";
	private String STOCK_ORDER_HEAD = "FOrdHed";
	private String STOCK_ORDER_DETAIL = "FOrddet";
	private String TEMPSTOCK_ORDER_HEAD = "TempFOrdHed";
	private String TEMPSTOCK_ORDER_DETAIL = "TempFOrddet";

	// Stock UnLoading
	private String TEMP_STOCK_LOADING_SUMMARYUN = "frepStockLoadingSummaryUn";
	private String STOCK_LOAD_HEADUN = "fUnLoadhed";
	private String STOCK_LOAD_DETAILUN = "fUnLoadDet";

	// Stock Damage
	private String TEMP_STOCK_LOADING_SUMMARYDAM = "frepStockLoadingSummaryDam";
	private String STOCK_LOAD_HEADDAM = "fDamhed";
	private String STOCK_LOAD_DETAILDAM = "fDamdet";

	// Cash /Cheque Receipt
	private String TEMP_RECEIPT_SUMMARY = "fReceiptSummary";
	private String RECEIPT_HEADER = "fDRecHed";
	private String RECEIPT_DETAILS = "fDRecDet";
	private String RECEIPT_INVOICES = "FDDbNote";

	final private static int DIALOG_CANCEL_INVOICE = 1;
	final private static int DIALOG_UNDO_INVOICE = 2;
	final private static int DIALOG_PRINT_INVOICE = 3;
	final private static int DIALOG_SAVE_INVOICE = 4;
	static final int DATE_DIALOG_ID = 0;
	private SQLiteDatabase mydb;
	AlertDialog InvoiceHeaderAlert = null;
	Button etdmreciptno, btnrecselectcustomer, btnselectrecpaytype,
			btnselectcusbank, btnSettleInvoices, btnselectchequedate;
	EditText etdmManualno, etdmreceiptdate, etdmreceiptcustomer,
			etdmreceiptpaytype, etdmreciptchequeno, etdmcustomerbank,
			etreceiptamount, etbalanceamount, etreceiptremark;
	double allocatingAmount = 0.0, UpdateAllocateBalAmt = 0.0,
			PendingBalance = 0.0;
	LinearLayout ListViewShowCustomers, ListViewReceiptHeaderButton,
			ListViewReceiptHeaderDetails, ListViewShowBankDetails,
			dmstloadStockLoadingList;
	private AlertDialog myDialog;
	private String[] items = { "CASH", "CHEQUE" };
	String receiptinvcuscode, receiptinvcusname, receiptinvcusdiscount,
			receiptbankcode, receiptbankname, receiptbanklocation,
			StockLoadingRef;

	String currentUserReceipt, currentUserPrefixLoad, currentUserLocation,
			PrintReceiptSerialStr, stlAgentPrefixType, StlTransTypePrefix,
			currentReceiptSerialStr, RepCashCheqReceiptCode,
			currentCashCheqReceiptRefCode;
	String treceiptusername, treceiptRefNo, treceiptManualno, detorcode,
			treceiptstartDate, treceiptCusno, treceiptPayType,
			treceiptChequeno, treceiptChequeDate, treceiptBankNo,
			treceiptReceiptAmt, treceiptReceiptBalAmt, treceiptRemark,
			UndoCurrentReceiptRef, UpdateReciptRefNo, TypeCode,
			deviceUser = "ANDROID", UserLocCode, UserAreaCode, UserDealCode,
			UserRouteCode;
	private int mYear, mMonth, mDay, mHour, mMinute;
	int position = 0, ActiveReceiptSerial, SAVERECTAG = 0, CANCELTAG = 0,
			SAVEDTAG = 0, DISPLAYSUMMARY = 0;
	DecimalFormat formatValues = new DecimalFormat("#,###,##0.00");

	public void ExitFromForm(View view) {
		Intent myIntent = new Intent(view.getContext(), DM_InvoiceMenu.class);
		myIntent.putExtra("TAGID", "SALES");
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();
	}

	public void btnStockLocationBack(View view) {
		ListViewReceiptHeaderButton.setVisibility(view.VISIBLE);
		ListViewReceiptHeaderDetails.setVisibility(view.VISIBLE);
		ListViewShowCustomers.setVisibility(view.GONE);
		dmstloadStockLoadingList.setVisibility(view.GONE);
	}

	// Print Customer Description
	public void AddCustomerDetails(View view) {
		Button des = (Button) view;
		String SetTransactionDesc = des.getText().toString();
		String[] accountdetail = SetTransactionDesc.split("/");
		receiptinvcuscode = accountdetail[0]; // invcuscode
		receiptinvcusname = accountdetail[1]; // invcusname
		receiptinvcusdiscount = accountdetail[2]; // invcusdiscount

		etdmreceiptcustomer.setText(receiptinvcusname);

		ListViewShowCustomers.setVisibility(view.GONE);
		dmstloadStockLoadingList.setVisibility(view.GONE);
		ListViewReceiptHeaderButton.setVisibility(view.VISIBLE);
		ListViewReceiptHeaderDetails.setVisibility(view.VISIBLE);
	}

	public void AddStockLoadingDetails(View view) {
		Button des = (Button) view;
		StockLoadingRef = des.getText().toString();
		etdmreciptno.setText(StockLoadingRef);
		ListViewReceiptHeaderButton.setVisibility(view.VISIBLE);
		ListViewReceiptHeaderDetails.setVisibility(view.VISIBLE);
		ListViewShowCustomers.setVisibility(view.GONE);
		dmstloadStockLoadingList.setVisibility(view.GONE);
		dmstloadStockLoadingList.setVisibility(view.GONE);

		StockLoadingRef = StockLoadingRef.trim();
		DISPLAYSUMMARY = 202;
		disableControls();
		populateStockLoadSummary();
		// populateStockLoadSummary2();
		populateStockLoadingList();
	}

	private void populateStockLoadSummary() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor sumStLoad = null;

		try {
			sumStLoad = mydb.query(TEMP_RECEIPT_SUMMARY, null, null, null,
					null, null, null);
		} catch (Exception e1) {
		}

		if (sumStLoad != null) {
			if (sumStLoad.getCount() > 0) {
				while (sumStLoad.moveToNext()) {
					String treceiptRefNo = sumStLoad.getString(5);

					if (StockLoadingRef.equals(treceiptRefNo.trim())) {
						String treceiptManualno = sumStLoad.getString(8);
						String treceiptstartDate = sumStLoad.getString(9);
						String treceiptCusName = sumStLoad.getString(11);
						String treceiptPayType = sumStLoad.getString(12);
						String treceiptChequeno = sumStLoad.getString(13);
						String treceiptChequeDate = sumStLoad.getString(14);
						String treceiptChequeBank = sumStLoad.getString(16);
						String treceiptRemark = sumStLoad.getString(19);
						etdmManualno.setText(treceiptManualno);
						etdmreceiptdate.setText(treceiptstartDate);
						etdmreceiptcustomer.setText(treceiptCusName);
						etdmreceiptpaytype.setText(treceiptPayType);
						etdmreciptchequeno.setText(treceiptChequeno);
						btnselectchequedate.setText(treceiptChequeDate);
						etdmcustomerbank.setText(treceiptChequeBank);
						etreceiptremark.setText(treceiptRemark);
					}

				}
			}
		}

	}

	private void disableControls() {
		// TODO Auto-generated method stub

	}

	// Print Banks Description
	public void AddBanksDetails(View view) {
		Button des = (Button) view;
		String SetTransactionDesc = des.getText().toString();
		String[] accountdetail = SetTransactionDesc.split("/");
		receiptbankcode = accountdetail[0]; // invcuscode
		receiptbankname = accountdetail[1]; // invcusname
		receiptbanklocation = accountdetail[3]; // invcusdiscount

		etdmcustomerbank.setText(receiptbankname);
		dmstloadStockLoadingList.setVisibility(view.GONE);
		ListViewShowBankDetails.setVisibility(view.GONE);
		ListViewReceiptHeaderButton.setVisibility(view.VISIBLE);
		ListViewReceiptHeaderDetails.setVisibility(view.VISIBLE);
	}

	// Back to Invoice header without selecting Customer
	public void btnCusListBack(View view) {
		dmstloadStockLoadingList.setVisibility(view.GONE);
		ListViewShowCustomers.setVisibility(view.GONE);
		ListViewShowBankDetails.setVisibility(view.GONE);
		ListViewReceiptHeaderButton.setVisibility(view.VISIBLE);
		ListViewReceiptHeaderDetails.setVisibility(view.VISIBLE);
	}

	// Get Current date and time for Alert Dialog
	public DM_Cash_Cheque_Receipt() {
		// Assign current Date and Time Values to Variables
		final Calendar c = Calendar.getInstance();
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);
		mHour = c.get(Calendar.HOUR_OF_DAY);
		mMinute = c.get(Calendar.MINUTE);
	}

	// =============Main Button Controllers================
	// *************Cancel Selected Receipt*****************
	public void btnCanclReceipt(View view) {
		checkReciptSaved();
		if (CANCELTAG == 45) {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_Cash_Cheque_Receipt.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("CANCEL INVALID RECEIPT");
			// Setting Dialog Message
			alertDialog.setMessage("Current Cash/Cheque Receipt Not Saved..");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					CANCELTAG = 0;
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		} else {
			if (etdmreciptno.length() != 0) {
				try {
					// ButtonTag = 3;
					showDialog(DIALOG_CANCEL_INVOICE);
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			} else {
				// ShowInvoiceList();//Will display current receipts
			}
		}

	}

	// *************Check Receipt Already Saved***********
	private void checkReciptSaved() {
		// TODO Auto-generated method stub
		String CurrentReceiptRefNoChk = etdmreciptno.getText().toString();
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		// String[] resultserial = { "tempRepInvSerial" };
		Cursor CurrentReceiptRefCur = null;
		try {
			CurrentReceiptRefCur = mydb.query(TEMP_RECEIPT_SUMMARY, null,
					"treceiptusername='" + currentUserReceipt
							+ "' AND treceiptRefNo='" + CurrentReceiptRefNoChk
							+ "' AND treceiptComplete ='2'", null, null, null,
					null);
		} catch (Exception e) {
		}
		if (CurrentReceiptRefCur != null) {
			if (CurrentReceiptRefCur.getCount() > 0) {
				CANCELTAG = 0;
			} else {
				CANCELTAG = 45;
			}
		}
		CurrentReceiptRefCur.close();
		mydb.close();
	}

	// Cancel Rejecting Current Receipt
	public void btnCancelInvoiceReject(View view) {
		// synchdata();
		InvoiceHeaderAlert.dismiss();
	}

	// *************Accept Cancel Cash Receipt Handling*************
	public void btnCancelInvoiceAccept(View view) {
		cancelCashReceiptRecord();
		Intent myIntent = new Intent(view.getContext(),
				DM_Cash_Cheque_Receipt.class);
		myIntent.putExtra("TAGID", "3");
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();
		return;
	}

	// Update cash receipt Cancel States
	private void cancelCashReceiptRecord() {
		// TODO Auto-generated method stub
		String CurrentReceiptRefNo = etdmreciptno.getText().toString();
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		// String[] resultserial = { "tempRepInvSerial" };
		Cursor saveStockLoadingMain = null;
		try {
			saveStockLoadingMain = mydb.query(TEMP_RECEIPT_SUMMARY, null,
					"treceiptusername='" + currentUserReceipt
							+ "' AND treceiptRefNo='" + CurrentReceiptRefNo
							+ "'", null, null, null, null);
		} catch (Exception e) {
		}
		if (saveStockLoadingMain != null) {
			if (saveStockLoadingMain.getCount() > 0) {
				while (saveStockLoadingMain.moveToNext()) {
					ContentValues valueupdateStLoadState = new ContentValues();
					String ReceiptCurrentid = saveStockLoadingMain.getString(0);
					valueupdateStLoadState.put("treceiptComplete", "5");
					mydb.update(TEMP_RECEIPT_SUMMARY, valueupdateStLoadState,
							"tempReceipt_id ='" + ReceiptCurrentid + "'", null);
					// saveNewStockLoadingRec();
				}

			}
		}
		saveStockLoadingMain.close();
		mydb.close();

	}

	// *************Undo Cash Receipt***********
	public void btnUndoReceipt(View view) {

		if (etdmreciptno.length() != 0) {
			try {
				showDialog(DIALOG_UNDO_INVOICE);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		} else {
			try {
				showDialog(DIALOG_UNDO_INVOICE);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}

	}

	// *************Undo Cash Receipt Handling*************
	public void btnUndoInvoiceCancel(View view) {
		// synchdata();
		InvoiceHeaderAlert.dismiss();
	}

	public void btnUndoInvoiceAccept(View view) {
		enableButtons();
		checkReceiptSaved();
		if (SAVEDTAG == 90) {
			if (etdmreciptno.length() != 0) {
				UpdateReceiptSummary();
				clearReceiptDet();
			}
		}
		if (DISPLAYSUMMARY == 202) {
			Intent myIntent = new Intent(view.getContext(),
					DM_Cash_Cheque_Receipt.class);
			myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_NEW_TASK);
			myIntent.putExtra("TAGID", "7");
			startActivityForResult(myIntent, 0);
			finish();
		}
		InvoiceHeaderAlert.dismiss();
	}

	// *************UndoExit Cash Receipt Handling*************
	public void btnUndoInvoiceAcceptExit(View view) {
		enableButtons();
		checkReceiptSaved();
		if (SAVEDTAG == 90) {
			if (etdmreciptno.length() != 0) {
				UpdateReceiptSummary();
				clearReceiptDet();
			}
		}
		InvoiceHeaderAlert.dismiss();
		Intent myIntent = new Intent(view.getContext(), DM_InvoiceMenu.class);
		myIntent.putExtra("TAGID", "SALES");
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();
	}

	// *************Print Cash Receipt***********
	public void btnPrintReceipt(View view) {
		checkReceiptSaved();
		if (SAVEDTAG == 102) {
			String currentPrintRefNo = etdmreciptno.getText().toString();
			Intent myIntent = new Intent(view.getContext(),
					DM_Print_Receipt.class);
			myIntent.putExtra("TAGIDREFNO", currentPrintRefNo);
			myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivityForResult(myIntent, 0);
			finish();
		} else {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_Cash_Cheque_Receipt.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("INVALID CASH RECEIPT");
			// Setting Dialog Message
			alertDialog.setMessage("Selected Cash Receipt Not Saved.");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		}
	}

	private void enableButtons() {
		// TODO Auto-generated method stub
		etreceiptamount.setEnabled(true);
		btnrecselectcustomer.setEnabled(true);
		btnselectrecpaytype.setEnabled(true);
		btnselectcusbank.setEnabled(true);
	}

	private void clearReceiptDet() {
		// TODO Auto-generated method stub
		etdmManualno.setText("");
		etdmreceiptcustomer.setText("");
		etdmreceiptpaytype.setText("");
		etdmreciptchequeno.setText("");
		btnselectchequedate.setText("");
		etdmcustomerbank.setText("");
		etreceiptamount.setText("");
		etbalanceamount.setText("");
		etreceiptremark.setText("");
	}

	private void UpdateReceiptSummary() {
		// TODO Auto-generated method stub
		UndoCurrentReceiptRef = etdmreciptno.getText().toString();
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor ChkCurrentReceiptCur = null;
		try {
			ChkCurrentReceiptCur = mydb.query(TEMP_RECEIPT_SUMMARY, null,
					"treceiptusername='" + currentUserReceipt
							+ "' AND treceiptActive='9'", null, null, null,
					null);
		} catch (Exception e) {
		}

		if (ChkCurrentReceiptCur != null) {
			if (ChkCurrentReceiptCur.getCount() > 0) {
				while (ChkCurrentReceiptCur.moveToNext()) {
					String ReferenceRecId = ChkCurrentReceiptCur.getString(0);
					ContentValues UpdateReceiptContent = new ContentValues();
					UpdateReceiptContent.put("treceiptComplete", "0");
					UpdateReceiptContent.put("treceiptActive", "9");
					UpdateReceiptContent.put("treceiptManualno", "");
					UpdateReceiptContent.put("treceiptstartDate",
							getCurrentTimeString());
					UpdateReceiptContent.put("treceiptCusno", "");
					UpdateReceiptContent.put("treceiptCusName", "");
					UpdateReceiptContent.put("treceiptPayType", "");
					UpdateReceiptContent.put("treceiptChequeno", "");
					UpdateReceiptContent.put("treceiptChequeDate", "");
					UpdateReceiptContent.put("treceiptBankNo", "");
					UpdateReceiptContent.put("treceiptBankName", "");
					UpdateReceiptContent.put("treceiptReceiptAmt", "0.00");
					UpdateReceiptContent.put("treceiptReceiptBalAmt", "0.00");
					UpdateReceiptContent.put("treceiptRemark", "");
					mydb.update(TEMP_RECEIPT_SUMMARY, UpdateReceiptContent,
							"tempReceipt_id=" + ReferenceRecId, null);
				}
			}
		}
		RemoveReceiptHeader();
		RemReciptDetUpdateReceipt();
	}

	private void RemoveReceiptHeader() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor ChkCurrentReceiptHedCur = null;
		try {
			ChkCurrentReceiptHedCur = mydb.query(RECEIPT_HEADER, null,
					"RefNo='" + UndoCurrentReceiptRef + "'", null, null, null,
					null);
		} catch (Exception e) {
		}

		if (ChkCurrentReceiptHedCur != null) {
			if (ChkCurrentReceiptHedCur.getCount() > 0) {
				while (ChkCurrentReceiptHedCur.moveToNext()) {
					mydb.delete(RECEIPT_HEADER, "RefNo ='"
							+ UndoCurrentReceiptRef + "'", null);
				}
			}
		}
		ChkCurrentReceiptHedCur.close();
		mydb.close();
	}

	// Remove Receipt Details and Update Receipt Deails Agestments
	private void RemReciptDetUpdateReceipt() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor ChkCurrentReceiptDetCur = null;
		try {
			ChkCurrentReceiptDetCur = mydb.query(RECEIPT_DETAILS, null,
					"RefNo='" + UndoCurrentReceiptRef + "'", null, null, null,
					null);
		} catch (Exception e) {
		}
		if (ChkCurrentReceiptDetCur != null) {
			if (ChkCurrentReceiptDetCur.getCount() > 0) {
				while (ChkCurrentReceiptDetCur.moveToNext()) {
					String ReferenceDetRecId = ChkCurrentReceiptDetCur
							.getString(0);
					UpdateReciptRefNo = ChkCurrentReceiptDetCur.getString(2);
					String BAmt = ChkCurrentReceiptDetCur.getString(14);
					UpdateAllocateBalAmt = Double.parseDouble(BAmt.replaceAll(
							"[,]", "").trim());
					// Update Recipt In to Original Value
					UpdateReciptAmountAgestment();

					mydb.delete(RECEIPT_DETAILS, "RecDet_id ='"
							+ ReferenceDetRecId + "'", null);
				}
			}
		}

	}

	private void UpdateReciptAmountAgestment() {
		// TODO Auto-generated method stub

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor ChkCurrentRecRefCur = null;
		try {
			ChkCurrentRecRefCur = mydb.query(RECEIPT_INVOICES, null, "RefNo='"
					+ UpdateReciptRefNo + "'", null, null, null, null);
		} catch (Exception e) {
		}
		if (ChkCurrentRecRefCur != null) {
			if (ChkCurrentRecRefCur.getCount() > 0) {
				while (ChkCurrentRecRefCur.moveToNext()) {
					String ReferenceReceiptRecId = ChkCurrentRecRefCur
							.getString(0);
					String BAmt = ChkCurrentRecRefCur.getString(16);
					String TotBal = ChkCurrentRecRefCur.getString(17);
					double BAmtValue = Double.parseDouble(BAmt.replaceAll(
							"[,]", ""));
					double TotBalValue = Double.parseDouble(TotBal.replaceAll(
							"[,]", ""));

					double newBAmt = BAmtValue + UpdateAllocateBalAmt;
					double newTotBal = TotBalValue + UpdateAllocateBalAmt;

					String newBAmtStr = Double.toString(newBAmt);
					String newnewTotBalStr = Double.toString(newTotBal);

					ContentValues UpdateReceiptBalance = new ContentValues();
					UpdateReceiptBalance.put("BAmt", newBAmtStr);
					UpdateReceiptBalance.put("TotBal", newnewTotBalStr);
					mydb.update(RECEIPT_INVOICES, UpdateReceiptBalance,
							"recinv_id=" + ReferenceReceiptRecId, null);
				}
			}
		}
	}

	// *************Print current Receipt*************
	public void btnPrintStloading(View view) {
		if (etdmreciptno.length() != 0) {
			checkReceiptSaved();
			if (SAVEDTAG == 102) {
				String currentPrintRefNo = etdmreciptno.getText().toString();
				Intent myIntent = new Intent(view.getContext(),
						DM_Print_Receipt.class);
				myIntent.putExtra("TAGIDREFNO", currentPrintRefNo);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
				finish();
			} else {
				final AlertDialog alertDialog = new AlertDialog.Builder(
						DM_Cash_Cheque_Receipt.this).create();
				// Setting Dialog Title
				alertDialog.setTitle("INVALID CASH RECEIPT");
				// Setting Dialog Message
				alertDialog.setMessage("Selected Cash Receipt Not Saved.");
				// Setting Icon to Dialog
				alertDialog.setIcon(R.drawable.warning);
				// Setting OK Button
				alertDialog.setButton("OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								alertDialog.dismiss();
							}
						});
				// Showing Alert Message
				alertDialog.show();
				alertDialog.setCanceledOnTouchOutside(false);
				return;
			}
		}
	}

	private void checkReceiptSaved() {
		// TODO Auto-generated method stub
		String currentPrintRefNo = etdmreciptno.getText().toString();
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor ChkReceiptSaved = null;
		try {
			ChkReceiptSaved = mydb.query(TEMP_RECEIPT_SUMMARY, null,
					"treceiptusername='" + currentUserReceipt
							+ "' AND treceiptComplete='2' AND treceiptRefNo ='"
							+ currentPrintRefNo + "'", null, null, null, null);
		} catch (Exception e) {
		}
		if (ChkReceiptSaved != null) {
			if (ChkReceiptSaved.getCount() > 0) {
				SAVEDTAG = 102;
			} else {
				SAVEDTAG = 90;
			}
		}
	}

	public void btnPrintInvoiceCancel(View view) {
		InvoiceHeaderAlert.dismiss();
	}

	public void btnPrintInvoiceAccept(View view) {
		InvoiceHeaderAlert.dismiss();
	}

	// *************Save Invoice*************
	public void btnSaveReceipt(View view) {
		String currentPendingBalance = etbalanceamount.getText().toString();
		PendingBalance = Double.parseDouble(currentPendingBalance.replaceAll(
				"[,]", ""));
		if (PendingBalance != 0.0) {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_Cash_Cheque_Receipt.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("INCOMPLETE ALLOCATION");
			// Setting Dialog Message
			alertDialog
					.setMessage("Allocate Balance Amount Received For Outstanding Invoices.");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
					return;
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		} else {
			saveCashChequeReceipt();
			try {
				showDialog(DIALOG_SAVE_INVOICE);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}

	private void saveCashChequeReceipt() {
		// TODO Auto-generated method stub
		SAVERECTAG = 10;
		UpdateSummaryRecordDetails();
		UpdateUserSettingsReceiptSerial();
		String currentReciptRefNo = etdmreciptno.getText().toString();
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor updateReciptSummary = null;
		try {
			updateReciptSummary = mydb.query(TEMP_RECEIPT_SUMMARY, null,
					"treceiptusername='" + currentUserReceipt
							+ "' AND treceiptActive='9'", null, null, null,
					null);
		} catch (Exception e) {
		}
		if (updateReciptSummary != null) {
			if (updateReciptSummary.getCount() > 0) {
				while (updateReciptSummary.moveToNext()) {
					treceiptusername = updateReciptSummary.getString(1);
					treceiptRefNo = updateReciptSummary.getString(5);
					treceiptManualno = updateReciptSummary.getString(8);
					treceiptstartDate = updateReciptSummary.getString(9);
					treceiptCusno = updateReciptSummary.getString(10);
					treceiptPayType = updateReciptSummary.getString(12);
					treceiptChequeno = updateReciptSummary.getString(13);
					treceiptChequeDate = updateReciptSummary.getString(14);
					treceiptBankNo = updateReciptSummary.getString(15);
					treceiptReceiptAmt = updateReciptSummary.getString(17);
					treceiptReceiptBalAmt = updateReciptSummary.getString(18);
					treceiptRemark = updateReciptSummary.getString(19);
					saveHeaderDetails();
				}
			}
		}
		enableButtons();

		updateReciptSummary.close();
		mydb.close();
	}

	private void UpdateUserSettingsReceiptSerial() {
		// TODO Auto-generated method stub
		currentUserStLoadChk();
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectUserSerial = null;

		try {
			selectUserSerial = mydb.query(INV_COMPANY_BRANCH, null,
					"cSettingsCode='HNBR' AND BranchCode='"
							+ currentUserReceipt + "'", null, null, null, null);
		} catch (Exception e) {
		}
		if (selectUserSerial != null) {
			if (selectUserSerial.getCount() > 0) {
				if (selectUserSerial.moveToLast()) {
					ContentValues updateNewSerial = new ContentValues();
					String serialStId = selectUserSerial.getString(0);
					updateNewSerial.put("nNumVal", currentReceiptSerialStr);
					mydb.update(INV_COMPANY_BRANCH, updateNewSerial,
							"fcombra_id ='" + serialStId + "'", null);
				}
			}
		}

	}

	private void saveHeaderDetails() {
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		// TODO Auto-generated method stub
		try {
			ContentValues addnewReceiptHeader = new ContentValues();
			addnewReceiptHeader.put("RefNo", etdmreciptno.getText().toString());
			addnewReceiptHeader.put("ManuRef", etdmManualno.getText()
					.toString());
			addnewReceiptHeader.put("SaleRefNo", "0");
			addnewReceiptHeader.put("RepCode", treceiptRefNo);
			addnewReceiptHeader.put("TxnType", "40");
			addnewReceiptHeader.put("Chqno", etdmreciptchequeno.getText()
					.toString());
			addnewReceiptHeader.put("ChqDate", btnselectchequedate.getText()
					.toString());
			addnewReceiptHeader.put("TxnDate", etdmreceiptdate.getText()
					.toString());
			addnewReceiptHeader.put("CurCode", "0");
			addnewReceiptHeader.put("CurRate", "1");
			addnewReceiptHeader.put("DebCode", receiptinvcuscode);
			addnewReceiptHeader.put("TotalAmt", treceiptReceiptAmt);
			addnewReceiptHeader.put("BTotalAmt", treceiptReceiptBalAmt);
			addnewReceiptHeader.put("BankCur", "0");
			addnewReceiptHeader.put("BankRate", "1");
			addnewReceiptHeader.put("BankAmt", "0");
			addnewReceiptHeader.put("BankCharge", "0");
			addnewReceiptHeader.put("BBankChg", "0");
			addnewReceiptHeader.put("GnLsCal", "0");
			addnewReceiptHeader.put("DbAcc", treceiptBankNo);
			String recPayType = etdmreceiptpaytype.getText().toString();
			if (recPayType.equals("CASH")) {
				addnewReceiptHeader.put("PayType", "CA");
			} else if (recPayType.equals("CHEQUE")) {
				addnewReceiptHeader.put("PayType", "CH");
			}
			addnewReceiptHeader.put("PrtCopy", "0");
			addnewReceiptHeader.put("GlPost", "0");
			addnewReceiptHeader.put("Remarks", "0");
			addnewReceiptHeader.put("CardSlipNo", "0");
			addnewReceiptHeader.put("ExpDate", "0");
			addnewReceiptHeader.put("CrdTypCode", "0");
			addnewReceiptHeader.put("CCBankAmt", "0");
			addnewReceiptHeader.put("GlBatch", "0");
			addnewReceiptHeader.put("AddUser", treceiptusername);
			addnewReceiptHeader.put("AddMach", deviceUser);
			addnewReceiptHeader.put("AddrecDate", getCurrentTimeString());
			addnewReceiptHeader.put("recipthedSync", "0");

			mydb.insert(RECEIPT_HEADER, null, addnewReceiptHeader);

		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Error Occured.." + e,
					Toast.LENGTH_SHORT).show();
		}
		mydb.close();
	}

	public void btnSaveInvoiceAccept(View view) {
		Intent myIntent = new Intent(view.getContext(), DM_InvoiceMenu.class);
		myIntent.putExtra("TAGID", "SALES");
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		myIntent.putExtra("TAGID", "8");
		startActivityForResult(myIntent, 0);
		InvoiceHeaderAlert.dismiss();
		finish();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_cash_cheque_receipt_hed);

		Bundle bundle = getIntent().getExtras();
		TagId = bundle.getString("TAGID");

		etdmreciptno = (Button) findViewById(R.id.etdmreciptno);
		btnrecselectcustomer = (Button) findViewById(R.id.btnrecselectcustomer);
		btnselectrecpaytype = (Button) findViewById(R.id.btnselectrecpaytype);
		btnselectcusbank = (Button) findViewById(R.id.btnselectcusbank);
		btnSettleInvoices = (Button) findViewById(R.id.btnSettleInvoices);
		btnselectchequedate = (Button) findViewById(R.id.btnselectchequedate);

		etdmManualno = (EditText) findViewById(R.id.etdmManualno);
		etdmreceiptdate = (EditText) findViewById(R.id.etdmreceiptdate);
		etdmreceiptcustomer = (EditText) findViewById(R.id.etdmreceiptcustomer);
		etdmreceiptpaytype = (EditText) findViewById(R.id.etdmreceiptpaytype);
		etdmreciptchequeno = (EditText) findViewById(R.id.etdmreciptchequeno);
		etdmcustomerbank = (EditText) findViewById(R.id.etdmcustomerbank);
		etreceiptamount = (EditText) findViewById(R.id.etreceiptamount);
		etreceiptamount.addTextChangedListener(calculateBalanceAmount);
		etbalanceamount = (EditText) findViewById(R.id.etbalanceamount);
		etreceiptremark = (EditText) findViewById(R.id.etreceiptremark);
		dmstloadStockLoadingList = (LinearLayout) findViewById(R.id.dmstloadStockLoadingList);
		ListViewShowCustomers = (LinearLayout) findViewById(R.id.dmreceiptselectcus);
		ListViewReceiptHeaderButton = (LinearLayout) findViewById(R.id.invheaderbuttons);
		ListViewReceiptHeaderDetails = (LinearLayout) findViewById(R.id.dmreceiptheadersection);
		ListViewShowBankDetails = (LinearLayout) findViewById(R.id.dmbanksselectreceipts);

		currentUserStLoadChk();// Check Current User
		stLoadingAgentPrefix();// Check Current Agent Prefix
		stLoadingTransType();// Check Current Trans Type
		checkLatestCashReceiptSerial();// Check Current Receipt
		populateCustomerList();
		populateBanksList();
		deviceName();

		etdmreciptno.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View view, MotionEvent motionevent) {

				int action = motionevent.getAction();
				if (action == MotionEvent.ACTION_DOWN) {
					clearReceiptDet();
					/*
					 * Toast.makeText(getApplicationContext(),
					 * "Button ACTION_DOWN", Toast.LENGTH_SHORT).show();
					 */
				} else if (action == MotionEvent.ACTION_UP) {
					dmstloadStockLoadingList.setVisibility(view.VISIBLE);
					ListViewShowCustomers.setVisibility(view.GONE);
					ListViewReceiptHeaderButton.setVisibility(view.GONE);
					ListViewReceiptHeaderDetails.setVisibility(view.GONE);
					ListViewShowBankDetails.setVisibility(view.GONE);
					populateStockLoadingList();
					// jana
				}
				return false;

			}

		});

		// Set ClickListener on btnSelectDate
		btnselectchequedate.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// Show the DatePickerDialog
				showDialog(DATE_DIALOG_ID);
			}
		});
		// ********Display Customer List*********
		btnrecselectcustomer.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				ListViewShowCustomers.setVisibility(view.VISIBLE);
				ListViewReceiptHeaderButton.setVisibility(view.GONE);
				ListViewReceiptHeaderDetails.setVisibility(view.GONE);
			}
		});
		// ********Display Banks List*********
		btnselectcusbank.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				ListViewShowBankDetails.setVisibility(view.VISIBLE);
				ListViewReceiptHeaderButton.setVisibility(view.GONE);
				ListViewReceiptHeaderDetails.setVisibility(view.GONE);
			}
		});
		// ********Display Payment Type List*********
		btnselectrecpaytype.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				myDialog.show();
			}
		});

		// ********Display Payment Type List Alert Dialog*********
		AlertDialog.Builder builder = new AlertDialog.Builder(
				DM_Cash_Cheque_Receipt.this);
		builder.setTitle("SELECT PAYMENT TYPE");
		builder.setIcon(R.drawable.cashreceipt);
		builder.setItems(items, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				String selectedType = items[which];
				if (selectedType.equals("CHEQUE")) {
					etdmreciptchequeno.setEnabled(true);
					btnselectchequedate.setEnabled(true);
					btnselectcusbank.setEnabled(true);
				} else {
					etdmreciptchequeno.setEnabled(false);
					btnselectchequedate.setEnabled(false);
					btnselectcusbank.setEnabled(false);
				}
				etdmreceiptpaytype.setText(items[which]);
			}
		});

		builder.setCancelable(false);
		myDialog = builder.create();

		// ********Settle Invoice Details Screen Navigation*********
		btnSettleInvoices.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				String allocAmt = etreceiptamount.getText().toString();
				double allocAmtVal = Double.parseDouble(allocAmt.replaceAll(
						"[,]", ""));

				if (etdmreceiptcustomer.length() == 0) {
					final AlertDialog alertDialog = new AlertDialog.Builder(
							DM_Cash_Cheque_Receipt.this).create();
					// Setting Dialog Title
					alertDialog.setTitle("SELECT CUSTOMER");
					// Setting Dialog Message
					alertDialog.setMessage("Select Customer From List");
					// Setting Icon to Dialog
					alertDialog.setIcon(R.drawable.warning);
					// Setting OK Button
					alertDialog.setButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									alertDialog.dismiss();
								}
							});
					// Showing Alert Message
					alertDialog.show();
					alertDialog.setCanceledOnTouchOutside(false);
					return;
				}

				if (etdmreceiptpaytype.length() == 0) {
					final AlertDialog alertDialog = new AlertDialog.Builder(
							DM_Cash_Cheque_Receipt.this).create();
					// Setting Dialog Title
					alertDialog.setTitle("ENTER PAY TYPE");
					// Setting Dialog Message
					alertDialog.setMessage("Enter Receipt Payment Method");
					// Setting Icon to Dialog
					alertDialog.setIcon(R.drawable.warning);
					// Setting OK Button
					alertDialog.setButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									alertDialog.dismiss();
								}
							});
					// Showing Alert Message
					alertDialog.show();
					alertDialog.setCanceledOnTouchOutside(false);
					return;
				}
				if (etdmreceiptpaytype.getText().toString().equals("CHEQUE")) {
					if (etdmreciptchequeno.length() == 0
							|| btnselectchequedate.length() == 0) {

						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_Cash_Cheque_Receipt.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("ENTER CHEQUE DETALS");
						// Setting Dialog Message
						alertDialog.setMessage("Enter Cheque Details");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										alertDialog.dismiss();
									}
								});
						// Showing Alert Message
						alertDialog.show();
						alertDialog.setCanceledOnTouchOutside(false);
						return;
					}
				}
				if (etreceiptamount.length() == 0 || allocAmtVal <= 0.0) {
					final AlertDialog alertDialog = new AlertDialog.Builder(
							DM_Cash_Cheque_Receipt.this).create();
					// Setting Dialog Title
					alertDialog.setTitle("ENTER ALLOCATING AMOUNT");
					// Setting Dialog Message
					alertDialog
							.setMessage("Enter Receipt Allocating Amount...");
					// Setting Icon to Dialog
					alertDialog.setIcon(R.drawable.warning);
					// Setting OK Button
					alertDialog.setButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									alertDialog.dismiss();
								}
							});
					// Showing Alert Message
					alertDialog.show();
					alertDialog.setCanceledOnTouchOutside(false);
					return;
				} else {
					UpdateSummaryRecordDetails();
					Intent myIntent = new Intent(view.getContext(),
							DM_Cash_Cheque_ReceiptDetails.class);
					myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
							| Intent.FLAG_ACTIVITY_NEW_TASK);
					myIntent.putExtra("TAGID", "7");
					startActivityForResult(myIntent, 0);
					finish();
				}
			}
		});

	}

	private void populateStockLoadingList() {
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.listviewPreStLoadList);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "coldes_1", "coldes_2" };
		int[] totrdes = new int[] { R.id.invListingViewNo,
				R.id.invListingViewSum };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowtypedes = null;
		try {
			String query = "SELECT * fROM fReceiptSummary Where treceiptComplete ='2'";
			allrowtypedes = mydb.rawQuery(query, null);
		} catch (Exception e) {
		}
		if (allrowtypedes != null) {
			if (allrowtypedes.getCount() > 0) {
				while (allrowtypedes.moveToNext()) {
					String stloadRef = allrowtypedes.getString(5);

					String rawitemsdet = stloadRef;
					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("coldes_1", rawitemsdet);
					maptrdes.put("coldes_2", stloadRef);
					fillMapstrdes.add(maptrdes);

				}
				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes, R.layout.dm_pre_stloading_list_raw,
						fromtrdes, totrdes);
				lvtypedes.setAdapter(adaptertrdes);
			}
		}
		allrowtypedes.close();
		mydb.close();
	}

	private void deviceName() {
		// TODO Auto-generated method stub
		String Model = android.os.Build.MODEL;
		String id = android.os.Build.ID;
		deviceUser = Model + "_" + id;
	}

	// ************Current User*****************
	private void currentUserStLoadChk() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectCurrentuserLoad = null;
		try {
			selectCurrentuserLoad = mydb.query(USER_SETTINGS, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (selectCurrentuserLoad != null) {
			if (selectCurrentuserLoad.getCount() > 0) {
				while (selectCurrentuserLoad.moveToNext()) {
					currentUserReceipt = selectCurrentuserLoad.getString(1);
					currentUserPrefixLoad = selectCurrentuserLoad.getString(2);
					currentUserLocation = selectCurrentuserLoad.getString(3);
					UserLocCode = selectCurrentuserLoad.getString(5);
					UserAreaCode = selectCurrentuserLoad.getString(9);
					UserDealCode = selectCurrentuserLoad.getString(10);
					UserRouteCode = selectCurrentuserLoad.getString(11);
					currentUserReceipt.trim();

				}
			}
		}
		selectCurrentuserLoad.close();
		mydb.close();
	}

	// ************Check Current Agent Prefix*****************
	private void stLoadingAgentPrefix() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectAgentPreType = null;

		try {
			selectAgentPreType = mydb.query(ITEM_CONTROL, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (selectAgentPreType != null) {
			if (selectAgentPreType.getCount() > 0) {
				while (selectAgentPreType.moveToNext()) {
					stlAgentPrefixType = selectAgentPreType.getString(18);
				}

			}
		}
		selectAgentPreType.close();
		mydb.close();
	}

	// ************Check Current Trans Type****************
	private void stLoadingTransType() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectTransType = null;

		try {
			selectTransType = mydb.query(ITEM_COMPANY_SETTING, null, null,
					null, null, null, null);
		} catch (Exception e) {
		}
		if (selectTransType != null) {
			if (selectTransType.getCount() > 0) {
				while (selectTransType.moveToNext()) {
					String cSettingsCode = selectTransType.getString(1);
					String cCharValue = selectTransType.getString(4);
					if (cSettingsCode.equals("HNBR")) {
						StlTransTypePrefix = cCharValue.trim();
					}
				}
			}
		}
		selectTransType.close();
		mydb.close();
	}

	private void checkLatestCashReceiptSerial() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectInvoiceSerial = null;

		try {
			selectInvoiceSerial = mydb.query(INV_COMPANY_BRANCH, null,
					"cSettingsCode='HNBR' AND BranchCode='"
							+ currentUserReceipt + "'", null, null, null, null);
		} catch (Exception e) {
		}

		Cursor selectLastinvrec = null;
		try {
			selectLastinvrec = mydb.query(TEMP_RECEIPT_SUMMARY, null,
					"treceiptusername='" + currentUserReceipt
							+ "' AND treceiptActive='9'", null, null, null,
					null);
		} catch (Exception e) {
		}

		if (selectInvoiceSerial != null) {
			if (selectInvoiceSerial.getCount() > 0) {
				while (selectInvoiceSerial.moveToNext()) {
					String cSettingsCode = selectInvoiceSerial.getString(3);
					String nNumVal = selectInvoiceSerial.getString(4);
					currentReceiptSerialStr = nNumVal.trim();
					if (selectLastinvrec != null) {
						if (selectLastinvrec.getCount() > 0) {
							if (selectLastinvrec.moveToLast()) {
								viewCurrentReceiptDetails();
							}
						} else if (selectLastinvrec.getCount() <= 0) {
							saveTempCashCheqReceipt();// Save Store Loading
						}
					}
				}
			} else {
				currentReceiptSerialStr = "1";
				try {
					ContentValues newAdjustment = new ContentValues();
					newAdjustment.put("BranchCode", currentUserReceipt);
					newAdjustment.put("RecordId", "1");
					newAdjustment.put("cSettingsCode", "HNBR");
					newAdjustment.put("nNumVal", currentReceiptSerialStr);
					mydb.insert(INV_COMPANY_BRANCH, null, newAdjustment);

					saveTempCashCheqReceipt();

				} catch (Exception e) {
					Toast.makeText(this, e.toString(), Toast.LENGTH_LONG)
							.show();
				}
				mydb.close();
			}
		}
		selectInvoiceSerial.close();
		mydb.close();
	}

	private void viewCurrentReceiptDetails() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		// String[] resultserial = { "tempRepInvSerial" };
		Cursor viewLastinvrec = null;
		try {
			viewLastinvrec = mydb.query(TEMP_RECEIPT_SUMMARY, null,
					"treceiptusername='" + currentUserReceipt
							+ "' AND treceiptActive='9'", null, null, null,
					null);
		} catch (Exception e) {
		}
		if (viewLastinvrec != null) {
			if (viewLastinvrec.getCount() > 0) {
				if (viewLastinvrec.moveToNext()) {
					PrintReceiptSerialStr = viewLastinvrec.getString(5);
					String treceiptManualno = viewLastinvrec.getString(8);
					String treceiptstartDate = viewLastinvrec.getString(9);
					String treceiptCusno = viewLastinvrec.getString(10);
					receiptinvcuscode = treceiptCusno.trim();
					String treceiptCusName = viewLastinvrec.getString(11);
					String treceiptPayType = viewLastinvrec.getString(12);
					String treceiptChequeno = viewLastinvrec.getString(13);
					String treceiptChequeDate = viewLastinvrec.getString(14);
					String treceiptBankNo = viewLastinvrec.getString(15);
					receiptbankcode = treceiptBankNo.trim();
					String treceiptBankName = viewLastinvrec.getString(16);
					String treceiptReceiptAmt = viewLastinvrec.getString(17);
					String treceiptReceiptBalAmt = viewLastinvrec.getString(18);
					String treceiptRemark = viewLastinvrec.getString(19);
					etdmreciptno.setText(PrintReceiptSerialStr);
					etdmManualno.setText(treceiptManualno);
					etdmreceiptdate.setText(treceiptstartDate);
					etdmreceiptcustomer.setText(treceiptCusName);
					etdmreceiptpaytype.setText(treceiptPayType);
					etdmreciptchequeno.setText(treceiptChequeno);
					btnselectchequedate.setText(treceiptChequeDate);
					etdmcustomerbank.setText(treceiptBankName);

					double treceiptReceiptAmtVal = Double
							.parseDouble(treceiptReceiptAmt.replaceAll("[,]",
									""));
					treceiptReceiptAmt = formatValues
							.format(treceiptReceiptAmtVal);
					etreceiptamount.setText(treceiptReceiptAmt);

					double treceiptReceiptBalAmtVal = Double
							.parseDouble(treceiptReceiptBalAmt.replaceAll(
									"[,]", ""));
					treceiptReceiptBalAmt = formatValues
							.format(treceiptReceiptBalAmtVal);
					etbalanceamount.setText(treceiptReceiptBalAmt);

					etreceiptremark.setText(treceiptRemark);
				}
			}
		}
		viewLastinvrec.close();
		mydb.close();
	}

	protected void UpdateSummaryRecordDetails() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor updateRecSummary = null;
		try {
			updateRecSummary = mydb.query(TEMP_RECEIPT_SUMMARY, null,
					"treceiptusername='" + currentUserReceipt
							+ "' AND treceiptActive='9'", null, null, null,
					null);
		} catch (Exception e) {
		}
		if (updateRecSummary != null) {
			if (updateRecSummary.getCount() > 0) {
				if (updateRecSummary.moveToNext()) {

					ContentValues curupdateRecSummary = new ContentValues();
					String recRid = updateRecSummary.getString(0);
					curupdateRecSummary.put("treceiptManualno", etdmManualno
							.getText().toString());
					curupdateRecSummary.put("treceiptstartDate",
							etdmreceiptdate.getText().toString());
					curupdateRecSummary.put("treceiptCusno", receiptinvcuscode);
					curupdateRecSummary.put("treceiptCusName",
							etdmreceiptcustomer.getText().toString());
					curupdateRecSummary.put("treceiptPayType",
							etdmreceiptpaytype.getText().toString());
					curupdateRecSummary.put("treceiptChequeno",
							etdmreciptchequeno.getText().toString());
					curupdateRecSummary.put("treceiptChequeDate",
							btnselectchequedate.getText().toString());
					curupdateRecSummary.put("treceiptBankNo", receiptbankcode);
					curupdateRecSummary.put("treceiptBankName",
							etdmcustomerbank.getText().toString());
					curupdateRecSummary.put("treceiptReceiptAmt",
							etreceiptamount.getText().toString());
					curupdateRecSummary.put("treceiptReceiptBalAmt",
							etbalanceamount.getText().toString());
					curupdateRecSummary.put("treceiptRemark", etreceiptremark
							.getText().toString());
					if (SAVERECTAG == 10) {
						curupdateRecSummary.put("treceiptComplete", "2");
						curupdateRecSummary.put("treceiptActive", "0");
						saveTempCashCheqReceipt();
					}
					mydb.update(TEMP_RECEIPT_SUMMARY, curupdateRecSummary,
							"tempReceipt_id ='" + recRid + "'", null);
				}
			}
		}
		updateRecSummary.close();
		mydb.close();
	}

	private void saveTempCashCheqReceipt() {
		// TODO Auto-generated method stub

		RepCashCheqReceiptCode = StlTransTypePrefix.trim()
				+ stlAgentPrefixType.trim() + currentUserPrefixLoad;
		if (SAVERECTAG == 10) {
			int tempRepReceiptSerialId = Integer
					.parseInt(currentReceiptSerialStr);
			int newReceiptSerialId = tempRepReceiptSerialId + 1;
			currentReceiptSerialStr = Integer.toString(newReceiptSerialId);
		}

		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		try {
			ContentValues saveCashCheqReceiptSummary = new ContentValues();
			saveCashCheqReceiptSummary.put("treceiptusername",
					currentUserReceipt);
			saveCashCheqReceiptSummary.put("treceiptprefix",
					currentUserPrefixLoad);
			saveCashCheqReceiptSummary.put("treceiptCode",
					RepCashCheqReceiptCode);
			saveCashCheqReceiptSummary.put("treceiptSerial",
					currentReceiptSerialStr);

			try {
				if (currentReceiptSerialStr.length() == 1) {
					String newInvNumberStr = "00000" + currentReceiptSerialStr;
					currentCashCheqReceiptRefCode = RepCashCheqReceiptCode
							.trim() + "/" + newInvNumberStr;
				} else if (currentReceiptSerialStr.length() == 2) {
					String newInvNumberStr = "0000" + currentReceiptSerialStr;
					currentCashCheqReceiptRefCode = RepCashCheqReceiptCode
							.trim() + "/" + newInvNumberStr;
				} else if (currentReceiptSerialStr.length() == 3) {
					String newInvNumberStr = "000" + currentReceiptSerialStr;
					currentCashCheqReceiptRefCode = RepCashCheqReceiptCode
							.trim() + "/" + newInvNumberStr;
				} else if (currentReceiptSerialStr.length() == 4) {
					String newInvNumberStr = "00" + currentReceiptSerialStr;
					currentCashCheqReceiptRefCode = RepCashCheqReceiptCode
							.trim() + "/" + newInvNumberStr;
				} else if (currentReceiptSerialStr.length() == 5) {
					String newInvNumberStr = "0" + currentReceiptSerialStr;
					currentCashCheqReceiptRefCode = RepCashCheqReceiptCode
							.trim() + "/" + newInvNumberStr;
				} else {
					String newInvNumberStr = currentReceiptSerialStr;
					currentCashCheqReceiptRefCode = RepCashCheqReceiptCode
							.trim() + "/" + newInvNumberStr;
				}
			} catch (Exception e) {

			}
			saveCashCheqReceiptSummary.put("treceiptRefNo",
					currentCashCheqReceiptRefCode);
			saveCashCheqReceiptSummary.put("treceiptComplete", "0");
			saveCashCheqReceiptSummary.put("treceiptActive", "9");
			saveCashCheqReceiptSummary.put("treceiptManualno", "");
			saveCashCheqReceiptSummary.put("treceiptstartDate",
					getCurrentTimeString());
			saveCashCheqReceiptSummary.put("treceiptCusno", "");
			saveCashCheqReceiptSummary.put("treceiptCusName", "");
			saveCashCheqReceiptSummary.put("treceiptPayType", "");
			saveCashCheqReceiptSummary.put("treceiptChequeno", "");
			saveCashCheqReceiptSummary.put("treceiptChequeDate", "");
			saveCashCheqReceiptSummary.put("treceiptBankNo", "");
			saveCashCheqReceiptSummary.put("treceiptBankName", "");
			saveCashCheqReceiptSummary.put("treceiptReceiptAmt", "0.00");
			saveCashCheqReceiptSummary.put("treceiptReceiptBalAmt", "0.00");
			saveCashCheqReceiptSummary.put("treceiptRemark", "");

			mydb.insert(TEMP_RECEIPT_SUMMARY, null, saveCashCheqReceiptSummary);

		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Record Not Insert..",
					Toast.LENGTH_SHORT).show();
		}
		mydb.close();
		viewCurrentReceiptDetails();
	}

	// **********Generate Banks List**********
	private void populateBanksList() {
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.listviewBankDetails);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "coldes_1", "coldes_2" };
		int[] totrdes = new int[] { R.id.receiptbankname, R.id.receiptbankdet };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curListBankers = null;
		try {
			curListBankers = mydb.query(BANK_DETAILS, null, null, null, null,
					null, null);
		} catch (Exception e) {
		}
		if (curListBankers != null) {
			if (curListBankers.getCount() > 0) {
				while (curListBankers.moveToNext()) {
					String bankcode = curListBankers.getString(2);
					String bankname = curListBankers.getString(3);
					String branchno = curListBankers.getString(4);
					String branchloc = curListBankers.getString(5);
					String columnBanksdet = bankcode + "/" + bankname + "/"
							+ branchno + "/" + branchloc;
					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("coldes_1", bankname);
					maptrdes.put("coldes_2", columnBanksdet);
					fillMapstrdes.add(maptrdes);

				}
				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes, R.layout.dm_bankers_list_raw, fromtrdes,
						totrdes);
				lvtypedes.setAdapter(adaptertrdes);
			}
		}
		curListBankers.close();
		mydb.close();
	}

	// **********Generate Customer List**********
	private void populateCustomerList() {
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.listviewcutommer);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "coldes_1", "coldes_2" };
		int[] totrdes = new int[] { R.id.invoicecustommer, R.id.invcustomername };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curListCustomer = null;
		try {
			String querySelectDebtor = "SELECT RD.DebCode,RD.RouteCode,FD.DebName,FD.OutDis FROM fRouteDet RD,fDebtor FD Where FD.DebCode = RD.DebCode AND RD.RouteCode ='"
					+ UserRouteCode + "'";
			curListCustomer = mydb.rawQuery(querySelectDebtor, null);
		} catch (Exception e) {
		}
		if (curListCustomer != null) {
			if (curListCustomer.getCount() > 0) {
				while (curListCustomer.moveToNext()) {
					String customercode = curListCustomer.getString(0);
					String customername = curListCustomer.getString(2);
					String customerdiscount = curListCustomer.getString(3);
					String columncusdet = customercode + "/" + customername
							+ "/" + customerdiscount;
					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("coldes_1", columncusdet);
					maptrdes.put("coldes_2", customername);
					fillMapstrdes.add(maptrdes);

				}
				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes, R.layout.dm_customer_list_raw,
						fromtrdes, totrdes);
				lvtypedes.setAdapter(adaptertrdes);
			}
		}
		curListCustomer.close();
		mydb.close();
	}

	// *****Calculation For Input Cases
	private TextWatcher calculateBalanceAmount = new TextWatcher() {

		public void afterTextChanged(Editable s) {

			if (etreceiptamount.length() != 0) {
				// Allocating Amount
				String allocatingAmountStr = etreceiptamount.getText()
						.toString();
				allocatingAmount = Double.parseDouble(allocatingAmountStr
						.replaceAll("[,]", ""));
				// Print Balance Amount
				String printBalanceAmountStr = Double
						.toString(allocatingAmount);

				double printBalanceAmountStrVal = Double
						.parseDouble(printBalanceAmountStr
								.replaceAll("[,]", ""));
				printBalanceAmountStr = formatValues
						.format(printBalanceAmountStrVal);
				etbalanceamount.setText(printBalanceAmountStr);

			} else {
				etbalanceamount.setText("");

			}
		}

		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			/*
			 * Toast.makeText(getApplicationContext(), "beforeTextChanged",
			 * Toast.LENGTH_SHORT).show();
			 */
		}

		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			/*
			 * Toast.makeText(getApplicationContext(), "onTextChanged",
			 * Toast.LENGTH_SHORT).show();
			 */
		}

	};

	// Handling Dialog Box Functions
	@Override
	protected Dialog onCreateDialog(int id) {

		switch (id) {
		case DIALOG_CANCEL_INVOICE:
			LayoutInflater inflater = LayoutInflater.from(this);
			View dialogview = inflater.inflate(
					R.layout.dm_dialog_cancel_invoice, null);

			AlertDialog.Builder dialogbuilder = new AlertDialog.Builder(this);
			dialogbuilder.setTitle("Cancel Current Cash Receipt Details...");
			dialogbuilder.setView(dialogview);
			InvoiceHeaderAlert = dialogbuilder.create();
			InvoiceHeaderAlert.setCanceledOnTouchOutside(false);
			break;

		case DIALOG_UNDO_INVOICE:
			LayoutInflater inflateru = LayoutInflater.from(this);
			View dialogviewu = inflateru.inflate(
					R.layout.dm_dialog_undo_invoice, null);

			AlertDialog.Builder dialogbuilderu = new AlertDialog.Builder(this);
			dialogbuilderu.setTitle("Undo Current Cash Receipt Details...");
			dialogbuilderu.setView(dialogviewu);
			InvoiceHeaderAlert = dialogbuilderu.create();
			InvoiceHeaderAlert.setCanceledOnTouchOutside(false);
			break;

		case DIALOG_PRINT_INVOICE:
			LayoutInflater inflaterp = LayoutInflater.from(this);
			View dialogviewp = inflaterp.inflate(
					R.layout.dm_dialog_saveprint_invoice, null);

			AlertDialog.Builder dialogbuilderp = new AlertDialog.Builder(this);
			dialogbuilderp.setTitle("Print Current Receipt...");
			dialogbuilderp.setView(dialogviewp);
			InvoiceHeaderAlert = dialogbuilderp.create();
			InvoiceHeaderAlert.setCanceledOnTouchOutside(false);
			break;

		case DIALOG_SAVE_INVOICE:
			LayoutInflater inflaters = LayoutInflater.from(this);
			View dialogviews = inflaters.inflate(
					R.layout.dm_dialog_saveprint_invoice, null);

			AlertDialog.Builder dialogbuilders = new AlertDialog.Builder(this);
			dialogbuilders.setTitle("Cash Receipt Saved Successfully...");
			dialogbuilders.setView(dialogviews);
			InvoiceHeaderAlert = dialogbuilders.create();
			InvoiceHeaderAlert.setCanceledOnTouchOutside(false);
			break;
		case DATE_DIALOG_ID:
			// create a new DatePickerDialog with values you want to show
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
					mDay);

		}

		return InvoiceHeaderAlert;
	}

	// Register DatePickerDialog listener
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		// the callback received when the user "sets" the Date in the
		// DatePickerDialog
		public void onDateSet(DatePicker view, int yearSelected,
				int monthOfYear, int dayOfMonth) {
			mYear = yearSelected;
			mMonth = monthOfYear;
			mDay = dayOfMonth;
			String mMonthStr = Integer.toString(mMonth);
			String mDayStr = Integer.toString(mDay);
			if (mMonthStr.length() == 1) {
				mMonthStr = "0" + mMonthStr;
			}
			if (mDayStr.length() == 1) {
				mDayStr = "0" + mDayStr;
			}
			// Set the Selected Date in Select date Button
			btnselectchequedate
					.setText(mDayStr + "/" + mMonthStr + "/" + mYear);
		}
	};

	// get current data and time
	private String getCurrentTimeString() {
		Calendar c = Calendar.getInstance();
		SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat("dd/MM/yyyy");
		String formattedDate = ddMMMyyFormat.format(c.getTime());
		return formattedDate;
	}
}